// WebPAC API
//
// Documented in this code only, I'm afraid. Beware of dragons!
// Dobrica Pavlinusic dpavlin(at)rot13(dot)org 2005-11-22

/*
	load another template
*/
function load_template(template_name) {

	var old_template = $('template_name').value;

	Logger.info('load_template: '+template_name+' (old: '+old_template+')');

	if (template_name == old_template) {
		Logger.error('why reload same template?');
		return false;
	}

	$('template_name').value = template_name;
	submit_results_form( 1 );
	return false;
}

/*
	pager
*/
function load_results_page(page_nr) {

	if (parseInt(page_nr) != page_nr) {
		Logger.error("load_results_page can't parseInt "+page_nr);
		return false;
	}

	var old_page = get_page_nr();

	if (page_nr < 1) {
		Logger.error("load_results_page called with '"+page_nr+"' < 1");
		return false;
	}

	Logger.info('load_results_page: '+page_nr+' (from page: '+old_page+')');

	if (page_nr == old_page) {
		Logger.error('why reload same page?');
		return false;
	}

	submit_results_form( page_nr );

	return false;
}

function get_page_nr() {
	var page_nr = parseInt( $('page_nr').value ) || 1;
	return page_nr;
}

function reset_page_nr( nr ) {
	if (! nr) nr = 1;
	Logger.info('reset_page_nr to '+nr);
	$('page_nr').value = nr;
}

/* syntaxtic sugar */
function set_page_nr(nr) {
	return load_results_page(nr);
}

function next_page() {
	load_results_page( get_page_nr() + 1 );
	return false;
}

function prev_page() {
	load_results_page( get_page_nr() - 1 );
	return false;
}

/* toggle visibility and replace text with something else */
function toggleLinkAndElement ( link, elementID, text ) {

	if ( link.innerHTML != text ) {
		// change link text
		link.oldInnerHTML = link.innerHTML;
		link.innerHTML = text;    
	} else {
		// change it back
		link.innerHTML = link.oldInnerHTML;
	}

	Logger.debug('toggleLinkAndElement '+elementID+': '+Element.visible( elementID )+' text: '+text);

	Element.toggle( elementID );

	// why is this needed, Firefox 1.5?
	if (Element.visible( elementID )) $( elementID ).style.display = 'block';

	return false;
}


/*
	submit results form using AJAX
*/
function submit_results_form( page_nr ) {
	var results_form = $('results_form');

	if (results_form) {
		var results_div = 'results';
		if (! page_nr) {
			page_nr = get_page_nr() || 0;
		} else {
			$('page_nr').value = page_nr;
			Logger.info("reset page_nr to "+page_nr);
		}

		if (page_nr > 1) {
			results_div += '_' + page_nr;
		}

		if (! $( results_div )) {
			Logger.error('next page div '+results_div+' doesn\'t exist');
			results_div = 'results';
		}

		var form_params = Form.serialize( results_form );
		var url = results_form.action;
		url += '/ajax';

		Logger.debug('submit_results_form to '+url+' page:'+page_nr+' div:'+results_div+' params:'+form_params);

		Logger.info( 'loading page '+page_nr+' into '+results_div );
		show_searching( page_nr );

		new Ajax.Updater( results_div, url, {
			parameters: form_params,
			asynchronous: 1,
			onComplete: function(request) {
				Logger.info( 'page '+page_nr+' loaded into '+results_div );
				update_results_stat( page_nr );
				hide_searching( page_nr );
			}
		} ) ;
		return false;
	} else {
		Logger.debug('no results_form element');
		return undef;
	}
	return false;
}

/*
	helper functions for submit_results_form()
*/

var search_active = 0;

function show_searching( page_nr ) {
	Logger.debug('show_searching '+page_nr);
	var el = 'searching';
	if (page_nr && page_nr > 1) el += '_'+page_nr;
	Element.show( el );
	search_active = 1;
	return false;
}

function hide_searching( page_nr ) {
	Logger.debug('hide_searching '+page_nr);
	var el = 'searching';
	if (page_nr && page_nr > 1) {
		Element.hide('page_'+(page_nr - 1));
	}
	Element.hide( el );
	search_active = 0;
//	new Effect.Appear('results', { duration: 0.3 });
	return false;
}

/*
	load record nr in some template
*/

function load_rec(record_uri, tmp_template_filename) {
	if (! tmp_template_filename) tmp_template_filename = template_filename;
	Logger.info('load_rec '+record_uri+' in '+tmp_template_filename);

	var results_form = $('results_form');

	if (results_form) {
		var args = '?record_uri='+record_uri+'&template_filename='+tmp_template_filename;
		Logger.debug('Ajax.Updater(results,/search/record) '+args);

		show_searching();

		new Ajax.Updater( 'results', '/search/record'+args, {
			asynchronous: 1,
			onComplete: function(request) {
				hide_searching();
			}
		} ) ;
		return false;
	} else {
		Logger.debug('no results_form element');
		return undef;
	}
	return false;
}

/* click on checkbox */

function checkbox_click() {
	if (search_active) return false;
	Logger.debug('checkbox_click');
	submit_results_form( 1 );
	return true;
}

/* toggle or select checkbox with value toggle */

function checkbox_toggle( name, val ) {
	return checkbox_magic( name, val, 0 );
}

var checkbox_single_current = '';

function checkbox_single( name, val ) {
	if (checkbox_single_current == name) {
		checkbox_single_current = '';
		Logger.debug('show all databases');
		return checkbox_magic( name, val, 0 );
	} else {
		Logger.debug('show just database '+name);
		checkbox_single_current = name;
		return checkbox_magic( name, val, 1 );
	}
}

function checkbox_magic( name, val, single ) {

	Logger.info('checkbox_magic('+name+','+val+','+single+')');

	var form = $('results_form');
	var inputs = form.getElementsByTagName('input');

	for (var i = 0; i < inputs.length; i++) {
		var input = inputs[i];
		if (input.type != 'checkbox') continue;
		if (single) {
			input.checked = false;
		}
		if (input.name != name || input.value != val) continue;
		Logger.debug('toggle '+input.name+'='+input.value+' '+input.checked);
		input.checked = ! input.checked;
		if (! single) {
			submit_results_form( 1 );
			return false;
		}
	}
	submit_results_form( 1 );
	return false;
}

/* reset form fields in _reset hidden field to nothing */

function reset_form() {
	Logger.info('reset '+$F('_reset'));

	var names = new Array();
	names = $F('_reset').split(',');
	for(var i = 0; i < names.length; i++) {
		Logger.debug('reset '+i+': '+names[i]);
		$(names[i]).value='';
	}

	var t=$('search_table');
	var max_p = t.rows.length;
	for(var i = 0; i < attr_rows.length; i++) {
		var p = attr_rows[i];
		if (p != -1) {
			if (p < max_p) {
				Logger.debug('delete row '+p);
				t.deleteRow( p );
			} else {
				Logger.error('skipping invalid delete row '+p);
			}
		}
	}

	attr_rows = new Array();

	return false;
}

/* helper function for [% search($display, $search, $delimiter) %] */

function search_via_link(attr, val, template) {

	if (! template) template = $('template_name').value;
	Logger.info('search called from link for '+attr+'='+val+' in '+template);
	save_search(attr, val);	

	$('template_name').value = template;
	submit_results_form( 1 );

	return false;
}

/* save search and add element for it in search form */

var attr_rows = new Array();

function save_search( attr, val ) {
	Logger.info('save_search('+attr+','+val+')');

	var t=$('search_table');
	if (! t) {
		Logger.error("can't find search_table");
		return undef;
	}
	reset_form();

	var form = $('results_form');
	var inputs = form.getElementsByTagName('input');

	for (var i = 0; i < inputs.length; i++) {
		var input = inputs[i];
		if (input.name != attr) continue;
		Logger.debug('found '+name+'='+input.value);
		input.value = unescape( val );
		return false;
	}

	var t_row_nr = t.rows.length;
	var tr = t.insertRow( t_row_nr );

	if (! tr) {
		Logger.error("can't create row "+t_row_nr);
		return undef;
	}

	var row_nr = attr_rows.length;
	attr_rows[ row_nr ] = t_row_nr;

	Logger.debug('added row '+t_row_nr+' to table [offset: '+row_nr+']');

	var td = tr.insertCell(0);
	td.setAttribute('align', 'right');
	td.appendChild(
		document.createTextNode(attr)
	);

	td = tr.insertCell(1);
	td.setAttribute('align', 'left');

	var el = document.createElement('input');
	el.setAttribute('type', 'text');
	// disabled fields are not submitted
	//el.setAttribute('disabled', 'true');
	el.setAttribute('name', attr);
	el.setAttribute('id', '_attr_'+attr+'_id');
	el.setAttribute('size', val.length < 60 ? 60: val.length);
	el.setAttribute('value', unescape( val ) );
	td.appendChild(el);

	var el = document.createElement('input');
	el.setAttribute('type', 'button');
	el.setAttribute('value', '-');
	el.onclick = function () {
		if (attr_rows[row_nr] == -1) {
			Logger.error('row '+row_nr+' allready deleted');
			return false;
		}
		Logger.info('remove:' + attr + ' row:'+row_nr+' ['+attr_rows[row_nr]+']');
		t.deleteRow( attr_rows[row_nr] );

		attr_rows[row_nr] = -1;
		for (var i=(row_nr + 1); i < attr_rows.length; i++) {
			attr_rows[i]--;
			Logger.debug('moved '+i+' to '+attr_rows[i]);
		}
		submit_results_form();
		return false;
	}
	td.appendChild(el);

	return true;
};

/* update number of results for each database */

function update_results_stat( page_nr ) {
	var el_name = 'node_results';
	var all_stats = new Array();
	var node_stat = new Array();

	var s_el = $( el_name );

	if ( s_el ) {
		all_stats = s_el.value.split(/ /);
		for (var i = 0; i < all_stats.length; i++) {
			node_stat = all_stats[i].split(/\//);
			var result_name = 'node_' + node_stat[0] + '_results';
			var u_el = $( result_name );
			if (u_el) {
				Logger.debug("node "+node_stat[0]+" has "+node_stat[1]+" results");
				u_el.innerHTML = node_stat[1] + '/';
				if (node_stat[1] == 0)
					Element.hide( 'node_'+node_stat[0] );
				else
					Element.show( 'node_'+node_stat[0] );
			} else {
				Logger.error("can't find " + result_name);
			}
		}
	} else {
		Logger.error("can't find element "+el_name);
	}
}

/* function which is called using DOM.Ready when html_results div is ready */

function results_ready( page_nr ) {
	if (! page_nr) page_nr = get_page_nr();
	Logger.info("html_results ready, page "+page_nr);
	update_results_stat( page_nr );
	var el = $( 'toggle_database_list' );
	if (el) {
		el.onclick()
	} else {
		Logger.error("can't find toggle_database_list");
	}
}

